package org.haredot.controller;

import org.haredot.annotation.LogModule;
import org.haredot.dto.UserDTO;
import org.haredot.service.UserService;
import org.haredot.vo.PageVo;
import org.haredot.vo.ResultVo;
import org.haredot.vo.UserVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@LogModule("用户管理")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService ;

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('user:view')")
    public ResultVo<?> list(@RequestParam("page") Integer page ,
                            @RequestParam("limits") Integer limits,
                            @RequestParam Map<String , ?> params) {

        PageVo<UserDTO> pageVo = new PageVo<>(page, limits) ;
        pageVo.setParams(params);

        return userService.queryUsers(pageVo);
    }

    @PostMapping("/{userId}/roles")
    @PreAuthorize("hasAuthority('user:view:bind:role')")
    public ResultVo<?> bindRoles(@PathVariable Long userId, @RequestBody List<Long> roles) {
        return userService.bindRoles(userId, roles);
    }

    @GetMapping("/departs")
    public ResultVo<?> queryDepartsRefUserId(@RequestParam(value = "uid", required = false) Long userId) {

        return userService.queryDepartsRefUserId(userId);
    }

    @GetMapping("/positions")
    public ResultVo<?> queryPositionsRefUserId(@RequestParam(value = "uid", required = false) Long userId) {

        return userService.queryPositionsRefUserId(userId);
    }

    @PostMapping("/{userId}/position")
    public ResultVo<?> bindPosition(@PathVariable Long userId,
                                    @RequestBody List<Long> positions) {
        return userService.bindPosition(userId, positions);
    }

    @GetMapping("/roles")
    @PreAuthorize("hasAuthority('user:view:bind:role')")
    public ResultVo<?> queryRoles(@RequestParam(value = "uid", required = false) Long userId) {

        return userService.queryRolesRefUserId(userId);
    }

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('user:view:add')")
    public ResultVo<?> addUser(@RequestBody UserVo user) {
        return userService.saveUser(user);
    }

    @PutMapping("/modify{userId}")
    @PreAuthorize("hasAuthority('user:view:modify')")
    public ResultVo<?> modifyUser(@PathVariable("userId") Long userId, @RequestBody UserVo user) {

        user.setId(userId);

        return userService.modifyUser(user);
    }

    @DeleteMapping("/remove/{userId}")
    @PreAuthorize("hasAuthority('user:view:remove')")
    public ResultVo<?> removeUser(@PathVariable Long userId) {

        return userService.removeUser(userId);
    }
}
